package com.um.psystem.controller.mtManage;

import cn.hutool.core.util.StrUtil;
import com.um.psystem.controller.BaseController;
import com.um.psystem.entity.ExcelHeader;
import com.um.psystem.entity.mtEntity.AssetsDetail;
import com.um.psystem.entity.mtEntity.AssetsType;
import com.um.psystem.entity.sysEntity.DeptEntity;
import com.um.psystem.entity.sysEntity.WsUser;
import com.um.psystem.enums.ResponseEnum;
import com.um.psystem.model.vo.DataGrid;
import com.um.psystem.model.vo.JsonResult;
import com.um.psystem.service.mtService.*;
import com.um.psystem.service.sysService.IDeptAndEmpService;
import com.um.psystem.service.sysService.IWsUserService;
import com.um.psystem.utils.EasyExcelUtils;
import com.um.psystem.utils.MyfileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author: zzj
 * @Description: 物资管理控制器
 * @Date: 2020/5/29
 */
@Controller
@RequestMapping(value = "/mtManage/assets")
public class AssetsManageController extends BaseController {

    @Autowired
    IAssetsTypeService iMtAssetsService;

    @Autowired
    IAssetsDetailService iAssetsDetailService;

    @Autowired
    IDeptAndEmpService iDeptAndEmpService;

    @Autowired
    IAssetsApplyService iAssetsApplyService;

    @Autowired
    IWsUserService iWsUserService;

    @Autowired
    IAssetsStockinService iAssetsStockinService;

    @Autowired
    IAssetsDeliveryService iAssetsDeliveryService;

    @Autowired
    IAssetsMonthlyService iAssetsMonthlyService;

    @Autowired
    IAssetsApplyRecordService iAssetsApplyRecordService;

    @Autowired
    IAssetsBalanceService iAssetsBalanceService;

    ////数据已存在
    //  throw new ApplicationException(StatusCode.CONFLICT.getCode(), StatusCode.CONFLICT.getMessage());

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping(value = "/list_main", method = RequestMethod.GET)
    public JsonResult getList() {
        return JsonResult.success(iMtAssetsService.getAssetsTypes(null));
    }

    /**
     * 物资一级分类列表(分页)
     *
     * @return
     */
    @RequestMapping(value = "/list_MainGrid", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid getMainGrid(@RequestParam Map map) {
        List<AssetsType> assetsTypeList = iMtAssetsService.getAssetsTypes(map);
        return buildDataGrid(assetsTypeList, assetsTypeList.size());
    }

    /**
     * 物资二级分类列表(分页)
     *
     * @param typeMainId
     * @return
     */
    @RequestMapping(value = "/list_DetailGrid", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid getDetailGrid(@RequestParam("typeMainId") String typeMainId, @RequestParam("typeDtlName") String typeDtlName) {
        Map<String, Object> modelMap = new HashMap();
        if (StrUtil.isNotBlank(typeMainId)) {
            modelMap.put("type_main_id", typeMainId);
        }
        if (StrUtil.isNotBlank(typeMainId)) {
            modelMap.put("type_dtl_name", typeDtlName);
        }
        List<AssetsDetail> assetsDetailList = iAssetsDetailService.getAssetsDetails(modelMap);
        return buildDataGrid(assetsDetailList, assetsDetailList.size());
    }

    /**
     * 物资二级分类列表(分页) 没有实体映射
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/list_Detail", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid getDetailGrid(@RequestParam Map map) {
        List<Map<String, Object>> assetsDetailList = iAssetsApplyService.getAssets(map);
        Integer total = 0;
        if(assetsDetailList.size()>0) {
            total = Integer.parseInt(assetsDetailList.get(0).get("totals").toString());
        }
        return buildDataGrid(assetsDetailList, total);
    }

    /**
     * 物资申请列表(分页)
     *
     * @param map
     * @return
     */

    @RequestMapping(value = "/list_applyGrid", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid getApplyGrid(@RequestParam Map map) {
        List<Map<String, Object>> apply_list = iAssetsApplyService.getApplyList(map);
        System.out.println(apply_list.size());
        int count = 0;
        if (apply_list != null && apply_list.size() > 0)
            count = Integer.parseInt(apply_list.get(0).get("totals").toString());
        return buildDataGrid(apply_list, count);
    }

    /**
     * 月度申请列表(分页)
     *
     * @param map
     * @return
     */

    @RequestMapping(value = "/list_monthlyGrid", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid getmonthlyGrid(@RequestParam Map map) {
        List<Map<String, Object>> MonCategory_list = iAssetsMonthlyService.getMonCategoryList(map);
        System.out.println(MonCategory_list.size());
        int count = 0;
        if (MonCategory_list != null && MonCategory_list.size() > 0)
            count = Integer.parseInt(MonCategory_list.get(0).get("totals").toString());
        return buildDataGrid(MonCategory_list, count);
    }

    /**
     * 月度申请填加类别
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/add_monCategory", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addmonCategory(@RequestParam Map map) {
        return iAssetsMonthlyService.addMonCategory(map);
    }

    /**
     * 添加物料信息（月度申请）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/add_assetsinfo", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addmonAssetsInfo(@RequestParam Map map) {
        return iAssetsMonthlyService.addmonAssetsInfo(map);
    }

    /**
     * 物资申请列表(通过ERP订单进行分类)
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/list_applyByErp", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid getApplyInfoByErp(@RequestParam Map map) {
        List<Map<String, Object>> apply_list = iAssetsApplyService.getApplyInfoList(map);
        System.out.println(apply_list.size());
        int count = 0;
        if (apply_list != null && apply_list.size() > 0)
            count = Integer.parseInt(apply_list.get(0).get("totals").toString());
        return buildDataGrid(apply_list, count);
    }

    /**
     * 物资月度申请列表(通过月份，分组)
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/list_monApply", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid getApplyInfoByMon(@RequestParam Map map) {
        List<Map<String, Object>> apply_list = iAssetsMonthlyService.getMonApplyInfoList(map);
        System.out.println(apply_list.size());
        int count = 0;
        if (apply_list != null && apply_list.size() > 0)
            count = Integer.parseInt(apply_list.get(0).get("totals").toString());
        return buildDataGrid(apply_list, count);
    }

    /**
     * 物资申请列表(条件筛选)
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/list_applyByScreen", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid getApplyInfoByScreen(@RequestParam Map map) {
        List<Map<String, Object>> apply_list = iAssetsApplyService.getApplyInfoByScreen(map);
        System.out.println(apply_list.size());
        int count = 0;
        if (apply_list != null && apply_list.size() > 0)
            count = Integer.parseInt(apply_list.get(0).get("totals").toString());
        return buildDataGrid(apply_list, count);
    }

    /**
     * 获取流程节点
     *
     * @return
     */
    @RequestMapping(value = "/list_flow", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid getFlowGrid(@RequestParam Map map) {
        List<Map<String, Object>> flow_list = iAssetsApplyService.getApplyNode(map);
        return buildDataGrid(flow_list, flow_list.size());
    }

    /**
     * 获取流程节点操作员
     *
     * @return
     */
    @RequestMapping(value = "/list_operator", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid getOperatorGrid(@RequestParam Map map) {
        List<Map<String, Object>> operator_list = iAssetsApplyService.getOperator(map);
        return buildDataGrid(operator_list, operator_list.size());
    }

    /**
     * 添加物资二级分类
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/add_DtlGrid", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addDtlGrid(@RequestParam Map map) {
        String type_main_name = map.get("type_main_name").toString();
        Integer type_main_id = Integer.parseInt(map.get("type_main_id").toString());
        String type_dtl_name = map.get("type_dtl_name").toString();
        String type_dtl_no = map.get("type_dtl_no").toString();

        String type_dtl_num = type_dtl_no.substring(type_dtl_no.length()-5,type_dtl_no.length()-1);
        Integer typeDtlNum = Integer.parseInt(type_dtl_num);
        System.out.println("type_dtl_num:" + type_dtl_num);
        String k3_no = map.get("k3_no").toString();
        String unit = map.get("unit").toString();
        String model = map.get("model").toString();
        String sizes = map.get("sizes").toString();
        String use_to = map.get("use_to").toString();
        String remark_dtl = map.get("remark_dtl").toString();
        String validation_flag = map.get("validation_flag").toString();
        String supplier = map.get("supplier").toString();
        String operator = map.get("operator").toString();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date_time = df.format(new Date());

        AssetsDetail assetsDetail = new AssetsDetail();
        assetsDetail.setModel(model);
        assetsDetail.setK3_code(k3_no);
        assetsDetail.setUnit(unit);
        assetsDetail.setUse_to(use_to);
        assetsDetail.setRemark(remark_dtl);
        assetsDetail.setSizes(sizes);
        assetsDetail.setTypeDtlName(type_dtl_name);
        assetsDetail.setTypeDtlNo(type_dtl_no);
        assetsDetail.setTypeDtlNum(typeDtlNum);
        assetsDetail.setTypeMainId(type_main_id);
        assetsDetail.setTypeMainName(type_main_name);
        assetsDetail.setValidation_flag(validation_flag);
        assetsDetail.setSupplier(supplier);
        assetsDetail.setOperator(operator);
        assetsDetail.setDate_time(date_time);
        if(iAssetsDetailService.getTypeDtlNoExist(type_dtl_no).equals("")){
            return iAssetsDetailService.save(assetsDetail);
        }else{
            return JsonResult.error(409,"编码已存在");
        }

    }

    /**
     * 添加物资申请
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/add_apply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addApply(@RequestParam Map map) {
        return iAssetsApplyService.save_apply(map);
    }

    /**
     * 添加物资申请(月度申请，一条空数据)
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/addMonApplyInfo_NULL", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addMonApply_null(@RequestParam Map map) {
        return iAssetsMonthlyService.saveMonApply_null(map);
    }

    /**
     * 根据分表的apply_order_info_id查找urgent_flag
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/getUrgentFlag", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getUrgentFlag(@RequestParam Map map) {
        return iAssetsApplyService.get_UrgentFlag(map);
    }

    /**
     * 修改物资申请
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update_apply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult upateApply(@RequestParam Map map) {
        return iAssetsApplyService.update_apply(map);
    }

    /**
     * 导入上个月数据
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/importMonthlyApplyData", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importMonthlyApplyData(@RequestParam Map map) {
        return iAssetsMonthlyService.importMonthlyApplyData(map);
    }


    /**
     * 提交申请
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/submit_apply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult submitApply(@RequestParam Map map) {
        return iAssetsApplyService.submitApply(map);
    }
    /**
     * 提交月度申请
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/submit_monthly_apply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult submitMonthlyApply(@RequestParam Map map) {
        return iAssetsMonthlyService.submitMonthlyApply(map);
    }

    /**
     * 审核月度申请
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/check_monthly_apply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult checkMonthlyApply(@RequestParam Map map) {
        return iAssetsMonthlyService.checkMonthlyApply(map);
    }

    /**
     * 打回月度申请
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/back_monthly_apply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult backMonthlyApply(@RequestParam Map map) {
        return iAssetsMonthlyService.backMonthlyApply(map);
    }

    /**
     * 按订单删除申请
     */
    @RequestMapping(value = "/del_apply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delApply(@RequestParam Map map) {
        return iAssetsApplyService.del_apply(map);
    }

    /**
     * 删除申请(月度)
     */
    @RequestMapping(value = "/del_monApply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delMonApply(@RequestParam Map map) {
        return iAssetsMonthlyService.del_monApply(map);
    }

    /**
     * 修改申请信息(月度)
     */
    @RequestMapping(value = "/update_monApplyInfo", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult update_monApplyInfo(@RequestParam Map map) {
        return iAssetsMonthlyService.update_monApplyInfo(map);
    }

    /**
     * 逐条删除
     */
    @RequestMapping(value = "/del_applyByOne", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delApplyByOne(@RequestParam Map map) {
        return iAssetsApplyService.del_applyByOne(map);
    }


    /**
     * 审核物资申请
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/check_apply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult checkApply(@RequestParam Map map) {
        return iAssetsApplyService.check_apply(map);
    }

    /**
     * 审核物资申请
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/back_apply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult backApply(HttpServletRequest request, @RequestParam Map map) {
        return iAssetsApplyService.back_apply(request, map);
    }

    /**
     * 发放物资
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/issue_apply", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult issueApply(HttpServletRequest request, @RequestParam Map map) {
        return iAssetsApplyService.issue_apply(request, map);
    }

    /**
     * 判断当前用户是否可以操作当前节点
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/judge_permission", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult judgePermission(String apply_id, String username, String flowNode) {
        return iAssetsApplyService.judgePermission(apply_id, username, flowNode);
    }

    /**
     * 判断当前用户是否可以进行编辑，删除
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/cheack_before", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult cheackBefore(@RequestParam Map map) {
        return iAssetsApplyService.cheackBefore(map);
    }

    /**
     * 添加物资一级分类
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/add_MainGrid", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addMainGrid(@RequestParam Map map) {
        String type_main_name = map.get("type_main_name").toString();
        String dept_name = map.get("dept_name").toString();
        String dept_id = map.get("dept_id").toString();
        String main_no = map.get("main_no").toString();
        String remark = map.get("remark").toString();
        AssetsType assetsType = new AssetsType();
        assetsType.setDeptId(dept_id);
        assetsType.setDeptName(dept_name);
        assetsType.setTypeMainNo(main_no);
        assetsType.setRemark(remark);
        assetsType.setTypeMainName(type_main_name);
        System.out.println(type_main_name + "&&&&" + dept_name);
        return iMtAssetsService.save(assetsType);
    }

    /**
     * 更新物资一级分类
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update_MainGrid", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult updateMainGrid(@RequestParam Map map) {
        String type_main_name = map.get("type_main_name").toString();
        Integer type_main_id = Integer.parseInt(map.get("type_main_id").toString());
        String dept_name = map.get("dept_name").toString();
        String dept_id = map.get("dept_id").toString();
        String main_no = map.get("main_no").toString();
        String remark = map.get("remark").toString();
        AssetsType assetsType = new AssetsType();
        assetsType.setDeptId(dept_id);
        assetsType.setDeptName(dept_name);
        assetsType.setTypeMainNo(main_no);
        assetsType.setRemark(remark);
        assetsType.setTypeMainName(type_main_name);
        assetsType.setTypeMainId(type_main_id);
        return iMtAssetsService.update(assetsType);
    }


    /**
     * 更新物资二级分类
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update_DtlGrid", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult updateDtlGrid(@RequestParam Map map) {
        String type_main_name = map.get("type_main_name").toString();
        Integer type_main_id = Integer.parseInt(map.get("type_main_id").toString());
        Integer type_dtl_id = Integer.parseInt(map.get("type_dtl_id").toString());
        String type_dtl_name = map.get("type_dtl_name").toString();
        String type_dtl_no = map.get("type_dtl_no").toString();
        String model = map.get("model").toString();
        String sizes = map.get("sizes").toString();
        String remark = map.get("remark_dtl").toString();
        String k3_no = map.get("k3_no").toString();
        String unit = map.get("unit").toString();
        String use_to = map.get("use_to").toString();
        String validation_flag = map.get("validation_flag").toString();
        String supplier = map.get("supplier").toString();
        String operator = map.get("operator").toString();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date_time = df.format(new Date());

        AssetsDetail assetsDetail = new AssetsDetail();
        assetsDetail.setModel(model);
        assetsDetail.setRemark(remark);
        assetsDetail.setSizes(sizes);
        assetsDetail.setTypeDtlName(type_dtl_name);
        assetsDetail.setTypeDtlNo(type_dtl_no);
        assetsDetail.setTypeMainId(type_main_id);
        assetsDetail.setTypeMainName(type_main_name);
        assetsDetail.setTypeDtlId(type_dtl_id);
        assetsDetail.setK3_code(k3_no);
        assetsDetail.setUnit(unit);
        assetsDetail.setUse_to(use_to);
        assetsDetail.setValidation_flag(validation_flag);
        assetsDetail.setSupplier(supplier);
        assetsDetail.setOperator(operator);
        assetsDetail.setDate_time(date_time);
        return iAssetsDetailService.update(assetsDetail);
    }

    /**
     * 部门列表
     *
     * @return
     */
    @RequestMapping(value = "/list_dept", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getDept() {
        List<DeptEntity> getDeptList = iDeptAndEmpService.getDeptList(null);
        //lamda表达式过滤掉无效数据
        getDeptList = getDeptList.stream().filter(o -> o.getDeptManager() != null)
                .filter(o -> o.getId() != 207).filter(o -> o.getIsDrop() != 1)
                .collect(Collectors.toList());
        //list存放map，map存放kv值（json），list取需要的字段
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (DeptEntity deptEntity : getDeptList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("dept_id", deptEntity.getId());
            map.put("dept_name", deptEntity.getDeptName());
            list.add(map);
        }
        return JsonResult.success(list);
    }

    /**
     * 销售订单列表
     *
     * @return
     */
    @RequestMapping(value = "/list_erp", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getErpList(@RequestParam Map map) {
        List<Map<String, Object>> getErpList = iAssetsApplyService.getErpNo(map);
        List<Map<String, Object>> list = new ArrayList<>();
        for (Map<String, Object> modelMap : getErpList) {
            Map<String, Object> mapvo = new HashMap<>();
            mapvo.put("conErpNo", modelMap.get("conErpNo").toString());
            list.add(mapvo);
        }
        return JsonResult.success(list);
    }

    /**
     * 获取新的物资编码
     *
     * @return
     */
    @RequestMapping(value = "/get_typeDtlNo", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getTypeDtlNo(@RequestParam Map map) {
        String typeDtlNo_new = iAssetsDetailService.getTypeDtlNo(map);
        return JsonResult.success(typeDtlNo_new);
    }

    /**
     * 销售订单列表
     *
     * @return
     */
    @RequestMapping(value = "/getErpInfo", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getErpInfo(@RequestParam Map map) {
        List<Map<String, Object>> getErpList = iAssetsApplyService.getErpNo(map);
        return JsonResult.success(getErpList);
    }

    /**
     * 销售订单列表
     *
     * @return
     */
    @RequestMapping(value = "/getErpInfoForPrint", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getErpInfoForPrint(@RequestParam Map map) {
        List<Map<String, Object>> getErpList = iAssetsApplyService.getErpInfoForPrint(map);
        return JsonResult.success(getErpList);
    }

    /**
     * 更新打印记录
     *
     * @return
     */
    @RequestMapping(value = "/insertPrintRecord", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult insertPrintRecord(@RequestParam Map map) {
        JsonResult<Integer> integerJsonResult = iAssetsApplyService.insertPrintRecord(map);
        return JsonResult.success(integerJsonResult);
    }


    /**
     * 职员列表
     *
     * @return
     */
    @RequestMapping(value = "/list_user", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getUserList() {
        Map paramsMap = new HashMap();
        paramsMap.put("visible", 1);
        List<WsUser> getUserList = iWsUserService.getUserList(paramsMap);
        //list存放map，map存放kv值（json），list取需要的字段
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (WsUser wsUser : getUserList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("user_id", wsUser.getId());
            map.put("user_name", wsUser.getUsername());
            list.add(map);
        }
        return JsonResult.success(list);
    }

    /**
     * 添加操作员信息
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/add_operator", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addOperator(@RequestParam Map map) {
        return iAssetsApplyService.save(map);
    }

    /**
     * 修改操作员信息
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update_operator", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult updateOperator(@RequestParam Map map) {
        return iAssetsApplyService.update(map);
    }

    /**
     * 添加操作员信息
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/add_flow", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addFlow(@RequestParam Map map) {
        return iAssetsApplyService.save_flow(map);
    }

    /**
     * 添加操作员信息
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update_flow", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult updateFlow(@RequestParam Map map) {
        return iAssetsApplyService.update_flow(map);
    }

    /**
     * 查询指定分类
     */
    @RequestMapping(value = "/getType/{typeMainId}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getType(@PathVariable Integer typeMainId) {
        return iMtAssetsService.get(typeMainId);
    }

    /**
     * 删除指定分类
     */
    @RequestMapping(value = "/delType/{typeMainId}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delType(@PathVariable Integer typeMainId) {
        return iMtAssetsService.del(typeMainId);
    }

    /**
     * 删除指定操作员
     */
    @RequestMapping(value = "/del_operator", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delOperator(@RequestParam Map map) {
        return iAssetsApplyService.del(map);
    }

    /**
     * 删除指定流程
     */
    @RequestMapping(value = "/del_flow", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delFLow(@RequestParam Map map) {
        return iAssetsApplyService.del_flow(map);
    }

    /**
     * 查询指定物资
     */
    @RequestMapping(value = "/delDtl/{typeDtlId}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delDtl(@PathVariable Integer typeDtlId) {
        return iAssetsDetailService.del(typeDtlId);
    }

    @GetMapping("/easyexceltest")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<ExcelHeader> headerList = new ArrayList<>();
        headerList.add(new ExcelHeader("text", "文字"));
        ExcelHeader dateHeader = new ExcelHeader("createTime", "时间");
        dateHeader.setDataType(ExcelHeader.DATE);
        dateHeader.setFormat("yyyy-MM-dd");
        headerList.add(dateHeader);
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<String, Object> modelMap = new HashMap<>();
            modelMap.put("text", "excel导出测试");
            modelMap.put("createTime", new Date());
            dataList.add(modelMap);
        }

        OutputStream excelOutputStream = EasyExcelUtils.exportDataToExcel(headerList, dataList);
        response.getOutputStream().write(((ByteArrayOutputStream) excelOutputStream).toByteArray());
    }

    /**
     * 物资申请excel数据导出
     *
     * @param response
     * @param map
     */
    @GetMapping("/exportApplyData")
    public void exportApplyData(HttpServletResponse response, @RequestParam Map map) {
        System.out.println(map);
        iAssetsApplyService.exportApplyData(response, map);
    }

    @GetMapping("/exportDelivetyData")
    public void exportDelivetyData(HttpServletResponse response, @RequestParam Map map) {
        System.out.println(map);
        iAssetsDeliveryService.exportDelivetyData(response, map);
    }

    @GetMapping("/exportStockData")
    public void exportStockData(HttpServletResponse response, @RequestParam Map map) {
        //解决GET请求中文乱码
        for (Object key : map.keySet())
        {
            String str = map.get(key).toString();
            try {
                map.put(key,new String(str.getBytes("ISO-8859-1"),"UTF-8"));
            }catch (UnsupportedEncodingException e)
            {e.printStackTrace();}
        }
        System.out.println(map);
        iAssetsStockinService.exportStockData(response, map);
    }

    /**
     * 物资月度申请excel数据导出
     *
     * @param response
     * @param map
     */
    @GetMapping("/exportMonthlyApplyData")
    public void exportMonthlyApplyData(HttpServletResponse response, @RequestParam Map map) {
        System.out.println(map);
        iAssetsMonthlyService.exportMonthlyApplyData(response, map);
    }

    /**
     * 物资入库列表第一次加载数据导入
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/list_stockinGrid", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid getStockinGrid(@RequestParam Map map) {
        //解决GET请求中文乱码
        for (Object key : map.keySet())
        {
            String str = map.get(key).toString();
            try {
                map.put(key,new String(str.getBytes("ISO-8859-1"),"UTF-8"));
            }catch (UnsupportedEncodingException e)
            {e.printStackTrace();}
        }

        List<Map<String, Object>> stockin_list = iAssetsStockinService.getStockinList(map);
        System.out.println(stockin_list.size());
        int count = 0;
        if (stockin_list != null && stockin_list.size() > 0)
            count = Integer.parseInt(stockin_list.get(0).get("totals").toString());
        return buildDataGrid(stockin_list, count);
    }

    /**
     * 查询K3编码对一个的物料相关信息
     */
    @RequestMapping(value = "/mtInfo", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getMtInfo(@RequestParam Map map) {
        List<Map<String, Object>> mtInfo_list = iAssetsStockinService.getMtInfo(map);
        if (mtInfo_list.size() > 0) {
            Map<String, Object> mtInfo_map = mtInfo_list.get(0);
            return JsonResult.success(mtInfo_map);
        } else {
            return JsonResult.error(ResponseEnum.NOT_FOUND);
        }
    }

    /**
     * 添加一条入库记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/addMtRecord", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addMtRecord(@RequestParam Map map) {
        JsonResult<Integer> integerJsonResult = iAssetsStockinService.addMtRecord(map);
        return integerJsonResult;
    }

    /**
     * 查询id对应的入库信息
     */
    @RequestMapping(value = "/recordInfo", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getRecordInfo(@RequestParam Map map) {
        List<Map<String, Object>> recordInfo_list = iAssetsStockinService.getRecordInfo(map);
        Map<String, Object> mtInfo_map = recordInfo_list.get(0);
        return new JsonResult(mtInfo_map);
    }

    /**
     * 更新一条入库记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/updateMtRecord", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult updateMtRecord(@RequestParam Map map) {
        JsonResult<Integer> integerJsonResult = iAssetsStockinService.updateMtRecord(map);
        return integerJsonResult;
    }

    /**
     * 删除入库记录(可以删除多条)
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/deleRecordInfo", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult deleMtRecord(@RequestParam Map map) {
        String ids = (String) map.get("ids");
        String[] idsArray = ids.split(",");
        for (String id : idsArray) {
            Integer integerId = Integer.parseInt(id);
            iAssetsStockinService.deleMtRecord(integerId);
        }
        return JsonResult.success(ResponseEnum.SUCCESS);
    }

    /**
     * 物资出库列表第一次加载数据导入
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/list_deliveryGrid", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid getDeliveryGrid(@RequestParam Map map) {
        List<Map<String, Object>> stockin_list = iAssetsDeliveryService.getDeliveryList(map);
        System.out.println(stockin_list.size());
        int count = 0;
        if (stockin_list != null && stockin_list.size() > 0)
            count = Integer.parseInt(stockin_list.get(0).get("totals").toString());
        return buildDataGrid(stockin_list, count);
    }

    /**
     * 添加一条出库记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/addMtDeliveryRecord", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addMtDeliveryRecord(@RequestParam Map map) {
        JsonResult<Integer> integerJsonResult = iAssetsDeliveryService.addMtDeliveryRecord(map);
        return integerJsonResult;
    }

    /**
     * 查询id对应的出库信息
     */
    @RequestMapping(value = "/deliveryInfo", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getDeliveryInfo(@RequestParam Map map) {
        List<Map<String, Object>> deliveryInfo_list = iAssetsDeliveryService.getDeliveryInfo(map);
        Map<String, Object> mtInfo_map = deliveryInfo_list.get(0);
        return new JsonResult(mtInfo_map);
    }
    /**
     * 修改出库记录状态
     */
    @RequestMapping(value = "/ChangeDeliveryState")
    @ResponseBody
    public JsonResult<Integer> ChangeDeliveryState(@RequestParam Map map) {
        map.put("state",1);
        JsonResult<Integer> res = iAssetsDeliveryService.updateMtDeliveryRecordState(map);
        return res;
    }

    /**
     * 更新一条出库记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/updateMtDeliveryRecord", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult updateMtDeliveryRecord(@RequestParam Map map) {
        JsonResult<Integer> integerJsonResult = iAssetsDeliveryService.updateMtDeliveryRecord(map);
        return integerJsonResult;
    }

    /**
     * 删除出库记录(可以删除多条)
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/deleDeliveryInfo", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult deleMtDeliveryRecord(@RequestParam Map map) {
        String ids = (String) map.get("ids");
        Integer success_count =0;
        String[] idsArray = ids.split(",");
        for (String id : idsArray) {
            Integer integerId = Integer.parseInt(id);
            JsonResult<Integer> jsonResult = iAssetsDeliveryService.deleMtDeliveryRecord(integerId);
            if (jsonResult.getCode().equals(200))
            {success_count++;}
        }
        return JsonResult.success(200,"本次共需删除"+idsArray.length+"项 成功"+success_count+"项(如有失败,失败项可能为已锁定)");
    }

    /**
     * 获取指定编码的库存数量
     *
     * @return
     */
    @RequestMapping(value = "/getStockinNum", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getStockinNum(@RequestParam Map map) {
        List<Map<String, Object>> getStockinList = iAssetsApplyService.getStockinNum(map);
        return JsonResult.success(getStockinList);
    }

    /**
     * 获取指定编码的库存数量和已申请数量（月度）
     *
     * @return
     */
    @RequestMapping(value = "/getStockinNumAndAppliedNum", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getStockinNumAndAppliedNum(@RequestParam Map map) {
        List<Map<String, Object>> listInfo = iAssetsMonthlyService.getStockinNumAndAppliedNum(map);
        return JsonResult.success(listInfo);
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult upload(@RequestParam("files") MultipartFile[] files, ModelMap map, @RequestParam Map map_id) {
        String id = map_id.get("rowid").toString();
        String username = map_id.get("username").toString();
        //清空指定目录（保证上传的是最新的文件）
        String path = MyfileUtils.directory+"/Acceptance_report/" + id;
        File file = new File(path);//创建文件类，指定要删除的文件夹路径
        MyfileUtils.remove(file);
        file.delete();//删除根目录,即要清空的那个文件夹
        if (!file.exists()) {
            System.out.println("删除成功");
        }

        List<String> results = MyfileUtils.uploadFile(files, id, id+"_"+username);
        if (results != null && results.size() > 0) {
            map.addAttribute("urls", results.get(0));
            return iAssetsStockinService.updateAppendixFlag(map_id,results.get(0));
        } else {
            return JsonResult.error(ResponseEnum.NOT_FOUND);
        }

    }

    @RequestMapping(value = "/list_applyRecord", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid getApplyRecord(@RequestParam Map map) {
        List<Map<String, Object>> apply_record_list = iAssetsApplyRecordService.getAssetsApplyRecord(map);
        int count = 0;
        if (apply_record_list != null && apply_record_list.size() > 0)
            count = Integer.parseInt(apply_record_list.get(0).get("totals").toString());
        return buildDataGrid(apply_record_list, count);
    }

    @RequestMapping(value = "/list_assetsBalance", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid getAssetsBalance(@RequestParam Map map) {
        List<Map<String, Object>> apply_record_list = iAssetsBalanceService.getAssetsBalance(map);
        int count = 0;
        if (apply_record_list != null && apply_record_list.size() > 0)
            count = Integer.parseInt(apply_record_list.get(0).get("totals").toString());
        return buildDataGrid(apply_record_list, count);
    }
}
